import React, { useState, useEffect } from 'react'
import { Editor } from "react-draft-wysiwyg";
import { EditorState, convertToRaw, ContentState } from 'draft-js';
import draftToHtml from 'draftjs-to-html';
import htmlToDraft from 'html-to-draftjs';
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";

export default function NewsEditor(props) {
    const [editorState, setEditorState] = useState(EditorState.createEmpty())

    useEffect(() => {
        const values = props.valueMap[1] === undefined ? '<p>Hey this <strong>editor</strong> rocks 😀</p>' : props.valueMap[1]
        const contentBlock = htmlToDraft(values);
        if (contentBlock) {
            const contentState = ContentState.createFromBlockArray(contentBlock.contentBlocks);
            const initState = EditorState.createWithContent(contentState);
            setEditorState(initState)
        }
        if (values != "<p></p>") {
            props.setSubmittableEvent(1, true)
            props.setvalueMapEvent(1, values)
        } else {
            props.setSubmittableEvent(1, false)
            props.setvalueMapEvent(1, values)
        }
    }, [])

    const onEditorStateChange = (editorState) => {
        setEditorState(editorState)
        const values = draftToHtml(convertToRaw(editorState.getCurrentContent())).trim("\n")
        if (values != "<p></p>") {
            props.setSubmittableEvent(1, true)
            props.setvalueMapEvent(1, values)
        } else {
            props.setSubmittableEvent(1, false)
            props.setvalueMapEvent(1, values)
        }
    }

    return (
        <Editor
            editorState={editorState}
            toolbarClassName="toolbarClassName"
            wrapperClassName="wrapperClassName"
            editorClassName="editorClassName"
            onEditorStateChange={(editorState) => { onEditorStateChange(editorState) }}
        />
    )
}
